/**
 * 
 */
package com.roc.web.action;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.opensymphony.xwork2.ActionSupport;
import com.roc.pojo.Operators;
import com.roc.pojo.LoginIpJnls;
import com.roc.pojo.ModuleCategory;
import com.roc.service.IMerchantServices;
import com.roc.service.IModuleService;
import com.roc.service.IUserService;
import com.roc.service.ServiceException;
import com.roc.util.Constance;
import com.roc.util.MD5Utils;
import com.roc.util.constant.Constant;
import com.roc.util.constant.OperatorsStatus;
import com.roc.util.constant.Role;

/**
 * @author Administrator
 * 
 */
@Component
@Namespace("/")
@Scope("prototype")
public class LoginAction extends ActionSupport {
	static Logger logger = LogManager.getLogger(LoginAction.class);

	private String msg;
	private Operators merchant;
	
	private String modifyFlag;
	private String passWord;
	private String newPassWord;
	private String rePassWord;
	
	
	@Autowired
	private IModuleService moduleService;
	@Autowired
	private IMerchantServices merchantServices;
	
	@Autowired
	private IUserService userService;

	@Action(value = "login", results = {
			@Result(name = "success", location = "/pages/host.jsp"),
			@Result(name = "login", location = "/login.jsp"),
			@Result(name = "init", location = "/init.jsp"),
			@Result(name = "error", location = "/login.jsp") }, interceptorRefs = @InterceptorRef("defaultStack")

	)
	
	public String login() throws Exception {
		Operators loginOperators=null;
		LoginIpJnls loginInfo = new LoginIpJnls();
		List<ModuleCategory> categoryList=new ArrayList<ModuleCategory>();
		HttpServletRequest request=ServletActionContext.getRequest();
		HttpSession session = request.getSession();
		try {
			
			 if(merchant==null) return LOGIN;
			 logger.info("----账号["+merchant.getAccountNo()+"]开始登陆----");
			/* String
			 checkCode_session=(String)session.getAttribute("checkCode");
			 if(checkCode_session==null||"".equals(checkCode_session)){
			 return LOGIN;
			 }*/
			/* if(checkCode==null||"".equals(checkCode)){
			 return LOGIN;
			 }
			 if(!checkCode.equals(checkCode_session)){
				 ServletActionContext.getRequest().setAttribute("info_request", "验证码输入有误，请重试...");
			 return LOGIN;
			 }*/
			 loginOperators=merchantServices.login(merchant);
			 
			 
			 if (loginOperators == null) {
				ServletActionContext.getRequest().setAttribute("info_request", "登陆账户不存在");
				
				return LOGIN;
			 }
			 if(loginOperators.getLastLoginTime()==null||loginOperators.getLastLoginTime()==""){
				 session.setAttribute(Constant.SESSION_LOGIN_MERCHANT, loginOperators);
				 merchant=loginOperators;
					return "init";
			 }
			 //大于90天修改密码
			 Date cDate = new Date();
			 Date sDate = DateUtils.addDays(cDate, -90);
			 String Dstr = DateFormatUtils.format(sDate, "yyyyMMdd");
			 if(loginOperators.getUpdatePWD()!=null&&!"".equals(loginOperators.getUpdatePWD())){
				 if(Long.valueOf(Dstr)>Long.valueOf(loginOperators.getUpdatePWD())){
					 session.setAttribute(Constant.SESSION_LOGIN_MERCHANT, loginOperators);
					 merchant=loginOperators;
					return "init";
				 } 
			 }
			
			
			
			String loginPassworld = MD5Utils.MD5Encode(merchant.getPwd());
			String merchantPassworld = loginOperators.getPwd();
			if (!loginPassworld.equals(merchantPassworld)) {
				ServletActionContext.getRequest().setAttribute("info_request", "账号或密码错误,请重试！");
				loginOperators.setPwdErrTimes(loginOperators.getPwdErrTimes()+1);
				merchantServices.loginAfter(loginOperators);
				logger.info("#########"+loginOperators.getAccountNo()+"登录密码错########");
				return LOGIN;
					
			}
			if(OperatorsStatus.CANCEL.getCode().equals(loginOperators.getStatus())){
				ServletActionContext.getRequest().setAttribute("info_request", "账户已注销，请联系客服人员！");
				
				return LOGIN;
			}
			if(OperatorsStatus.WAIT_AUDITING.getCode().equals(loginOperators.getStatus())||
					OperatorsStatus.WAIT_RE_AUDITING.getCode().equals(loginOperators.getStatus())||
					OperatorsStatus.INCOMPLETE_INFO.getCode().equals(loginOperators.getStatus())){
				ServletActionContext.getRequest().setAttribute("info_request", "账户审核中，请联系客服人员！");
				return LOGIN;
			}
			String validDate=Constance.formatDate(Constance.DATA_FORMAT_PATTERN_01);
			if(validDate.compareTo(loginOperators.getValidEndDate())>0){
				ServletActionContext.getRequest().setAttribute("info_request", "账户已过期，请联系客服人员！");
				return LOGIN;
			}
			if(loginOperators.getPwdErrTimes()>10){
				ServletActionContext.getRequest().setAttribute("info_request", "密码错误次数过多，请隔日再试");
				
				return LOGIN;
			}
			loginOperators.setLastLoginTime(Constance.formatDate(Constance.DATA_FORMAT_PATTERN_01));
			
			merchantServices.loginAfter(loginOperators);
			logger.info("#########"+loginOperators.getAccountNo()+"登录正常########");
			
			categoryList=moduleService.listMenuByMerchantNo(merchant);
			loginOperators.setMenuList(categoryList);
			loginOperators.setRoleName(Role.valueOfCode(loginOperators.getRoleType()).getName());
			session.setAttribute(Constant.SESSION_LOGIN_MERCHANT, loginOperators);
			logger.info("----登陆成功----");
			
			//记录登录信息
			String ip=getIpAddr(request);
			logger.info("----ip="+ip);
			loginOperators.setLoginIp(ip);	
			loginInfo.setAddress(ip);
			loginInfo.setAgentId(loginOperators.getId());
			loginInfo.setLoginTime(Constance.formatDate(Constance.DATA_FORMAT_PATTERN_01));
			userService.insertLoginInfo(loginInfo);
			logger.info("----保存登录信息成功----");
			
		} catch (ServiceException e) {
			ServletActionContext.getRequest().setAttribute("info_request", e.getMessage());
		   logger.error(e.getMessage(), e);
		   return ERROR;
		}
		//System.out.println("sddddddddddddddd");
		return SUCCESS;
	}

	@Action(value = "logout", results = {
			@Result(name = "success", location = "/pages/redirect.jsp"),
			@Result(name = "input", location = "/pages/redirect.jsp"),
			@Result(name = "error", location = "/pages/redirect.jsp") })
	public String logout() throws Exception {
		try{
			HttpServletRequest request=ServletActionContext.getRequest();
			HttpSession session = request.getSession();
			Operators loginOperators=(Operators)session.getAttribute(Constant.SESSION_LOGIN_MERCHANT);
			logger.info("###########操作员【"+loginOperators.getAccountNo()+"】正常退出################");
			ServletActionContext.getRequest().getSession().invalidate();
			logger.info("###########destoryed session ################");
			
		}catch (Exception e) {
			// TODO: handle exception
			logger.info("###########destoryed session exception  ################");
			
			logger.error(e.getMessage(),e);
			e.printStackTrace();
			
		}
		
		return SUCCESS;
	}
	
	@Action(value = "modify", results = {
			@Result(name = "success", location = "/pages/modify.jsp"),
			@Result(name = "input", location = "/pages/redirect.jsp"),
			@Result(name = "error", location = "/error.jsp") })
	public String modify() throws Exception {
		Operators merchant=(Operators)ServletActionContext.getRequest().getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if(merchant==null){
			return INPUT;
		}
		return SUCCESS;
	}
	@Action(value = "mSubmit", results = {
			@Result(name = "success", location = "/pages/modify.jsp"),
			@Result(name = "input", location = "/pages/redirect.jsp"),
			@Result(name = "error", location = "/pages/modify.jsp") })
	public String modifySubmit() throws Exception {
		Operators merchant=(Operators)ServletActionContext.getRequest().getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if(merchant==null){
			return INPUT;
		}
		if("1".equals(modifyFlag)){
			if(!merchant.getPwd().equals(MD5Utils.MD5Encode(passWord))){
				msg="原密码不正确！！！";
				return SUCCESS;
			}
			if(!newPassWord.equals(rePassWord)){
				msg="新密码与确认密码不一致，请重新输入！！！";
				return SUCCESS;
			}
			
			String str = "0sd00e23s";
			int j=0;
			if (newPassWord != null && Pattern.compile("[a-z]").matcher(newPassWord).find()) { 
			    // 有字母 
			   j++;
			}
			
			if (newPassWord != null && Pattern.compile("(?i)[0-9]").matcher(newPassWord).find()) { 
			    // 有 数字
			   j++;
			}
	/*		//
			String regex = "[\\`\\~\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)\\-\\_\\=\\+\\[\\]\\{\\}\\\\\\|\\;\\:\\'\"\\,\\<\\.\\>\\/\\?]";
			if (newPassWord != null && Pattern.compile(regex).matcher(newPassWord).find()) { 
			    // 有 特殊字符
			   j++;
			}*/
			if(j<2){
				msg="新密码必须包含小写英文和数字！请重新输入";
				return SUCCESS;
			}
			if(newPassWord.length() < 8 || newPassWord.length() > 12){
				msg="密码不能少于8位，不能大于12位！请重新输入";
				return SUCCESS;
			}
			
			merchant.setPwd(MD5Utils.MD5Encode(newPassWord));
			String time = "";
			Date dt = new Date();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			time = sdf.format(dt);
			merchant.setUpdatePWD(time);
			try {
				merchant=merchantServices.modifyPwd(merchant);
				ServletActionContext.getRequest().getSession().setAttribute(Constant.SESSION_LOGIN_MERCHANT, merchant);
				msg="密码修改成功";
				logger.info("------------代理商【"+merchant.getAccountNo()+"】修改密码成功！---------------");
			
			} catch (ServiceException e) {
				 msg=e.getMessage();
				logger.info("------------代理商【"+merchant.getAccountNo()+"】修改密码失败！---------------");
			    logger.error(e.getMessage(),e);
			    return SUCCESS;
			}
		}
		return SUCCESS;
	}
	@Action(value = "initSbt", results = {
			@Result(name = "success", location = "/pages/redirect.jsp"),
			@Result(name = "input", location = "/init.jsp"),
			@Result(name = "error", location = "/error.jsp") })
	public String initSbt() throws Exception {
		Operators operators=(Operators)ServletActionContext.getRequest().getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
			if(merchant==null){
				addActionError("账号不存在，请重试！！！");
				return INPUT;
			}
			String ip=ServletActionContext.getRequest().getRemoteAddr();
			operators.setLoginIp(ip);
			
			if(!operators.getPwd().equals(MD5Utils.MD5Encode(passWord))){
				addActionError("初始密码不正确");
				return INPUT;
			}
			if(!newPassWord.equals(rePassWord)){
				addActionError("新密码与确认密码不一致，请重新输入！！！");
				return INPUT;
			}

			int j=0;
			if (newPassWord != null && Pattern.compile("[a-z]").matcher(newPassWord).find()) { 
			    // 有字母 
			   j++;
			}
			
			if (newPassWord != null && Pattern.compile("(?i)[0-9]").matcher(newPassWord).find()) { 
			    // 有 数字
			   j++;
			}
		/*	//
			String regex = "[\\`\\~\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)\\-\\_\\=\\+\\[\\]\\{\\}\\\\\\|\\;\\:\\'\"\\,\\<\\.\\>\\/\\?]";
			if (newPassWord != null && Pattern.compile(regex).matcher(newPassWord).find()) { 
			    // 有 特殊字符
			   j++;
			}*/
			if(j<2){
				addActionError("新密码必须包含小写英文和数字！请重新输入");
			//	return INPUT;
				return ERROR;
			}
			if(newPassWord.length() < 8 || newPassWord.length() > 12){
				addActionError("密码不能少于8位，不能大于12位！请重新输入");
				return ERROR;
			}
			operators.setLastLoginTime(Constance.formatDate(Constance.DATA_FORMAT_PATTERN_01));
			
			operators.setPwd(MD5Utils.MD5Encode(newPassWord));
			
			try {
				merchantServices.modifyPwd(operators);
				ServletActionContext.getRequest().getSession().removeAttribute(Constant.SESSION_LOGIN_MERCHANT);
				addActionMessage("【"+operators.getAccountNo()+"】修改密码成功！");
				logger.info("------------【"+operators.getAccountNo()+"】修改密码成功！---------------");
			
			} catch (ServiceException e) {
				
				logger.info("------------【"+operators.getAccountNo()+"】修改密码失败！---------------");
			    logger.error(e.getMessage(),e);
			    addActionError(e.getMessage());
			    return ERROR;
			}
		
		return SUCCESS;
	}
	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}



/*	*//**
	 * @param checkCode
	 *            the checkCode to set
	 *//*
	public void setCheckCode(String checkCode) {
		this.checkCode = checkCode;
	}*/

	/**
	 * @return the merchant
	 */
	public Operators getMerchant() {
		return merchant;
	}

	/**
	 * @param merchant the merchant to set
	 */
	public void setMerchant(Operators merchant) {
		this.merchant = merchant;
	}

	/**
	 * @return the modifyFlag
	 */
	public String getModifyFlag() {
		return modifyFlag;
	}

	/**
	 * @param modifyFlag the modifyFlag to set
	 */
	public void setModifyFlag(String modifyFlag) {
		this.modifyFlag = modifyFlag;
	}

	/**
	 * @return the passWord
	 */
	public String getPassWord() {
		return passWord;
	}

	/**
	 * @param passWord the passWord to set
	 */
	public void setPassWord(String passWord) {
		this.passWord = passWord;
	}

	/**
	 * @return the newPassWord
	 */
	public String getNewPassWord() {
		return newPassWord;
	}

	/**
	 * @param newPassWord the newPassWord to set
	 */
	public void setNewPassWord(String newPassWord) {
		this.newPassWord = newPassWord;
	}

	/**
	 * @return the rePassWord
	 */
	public String getRePassWord() {
		return rePassWord;
	}

	/**
	 * @param rePassWord the rePassWord to set
	 */
	public void setRePassWord(String rePassWord) {
		this.rePassWord = rePassWord;
	}
	
	


    private String getIpAddr(HttpServletRequest  request) {   
         String ipAddress = null;   
         //ipAddress = this.getRequest().getRemoteAddr();   
         ipAddress = request.getHeader("x-forwarded-for");   
         if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {   
          ipAddress = request.getHeader("Proxy-Client-IP");   
         }   
         if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {   
             ipAddress = request.getHeader("WL-Proxy-Client-IP");   
         }   
         if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {   
          ipAddress = request.getRemoteAddr();   
          if(ipAddress.equals("127.0.0.1")){   
           //根据网卡取本机配置的IP   
           InetAddress inet=null;   
        try {   
         inet = InetAddress.getLocalHost();   
        } catch (UnknownHostException e) {   
         logger.error("获取ip 失败",e);  
        }   
        ipAddress= inet.getHostAddress();   
          }   
                
         }   
      
         //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割   
         if(ipAddress!=null && ipAddress.length()>15){ //"***.***.***.***".length() = 15   
             if(ipAddress.indexOf(",")>0){   
                 ipAddress = ipAddress.substring(0,ipAddress.indexOf(","));   
             }   
         }   
         return ipAddress;    
      }   



}
